package com.example.demo.common.intercepor;


import com.example.demo.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //校验token是否正确
        //获取token
        String token = request.getHeader("user_header_token");
        log.info("从header中获取到token, token:{}", token);
        //校验token是否存在
        Claims claims = JwtUtil.parseToken(token);
        //token不合法
        if(claims == null){
            response.setStatus(401);
            return false;
        }
        //TODO 也可以再做的细一点
        //比如校验id和name是否匹配, 是否存在
        //claims.get("name")
        return true;
    }
}
